package com.example.birdfriends.utils.message;


import com.example.birdfriends.pojo.message.Message;
import com.example.birdfriends.pojo.message.MessageAndFriend;
import com.example.birdfriends.pojo.message.MessageVo;
import com.example.birdfriends.pojo.user.User;
import com.example.birdfriends.service.MessageService;
import com.example.birdfriends.service.UserService;
import com.example.birdfriends.utils.convert.ConvertService;
import com.example.birdfriends.utils.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class MessageUtil {
    public List<Message> mergeMessageList(List<Message> messages1, List<Message> messages2){
        List<Message> messages = new ArrayList<>();
        messages.addAll(messages1);
        messages.addAll(messages2);
        messages.sort((t1, t2) -> t2.getCreateAt().compareTo(t1.getCreateAt()));
        Collections.reverse(messages);
        return messages;
    }

    @Autowired
    private MessageService messageService;
    @Autowired
    private ConvertService convertService;
    @Autowired
    private UserService userService;

    public MessageAndFriend findFriendAndMessage(Message message, String curPage){
        MessageVo messageVo = convertService.message2MessageVo(message, curPage);  // 转换消息
        Long senderId = message.getSenderId();  // 发送者的id
        User sender = userService.findUserByUid(senderId);  // 好友信息
        sender.setPassword("");
        MessageAndFriend messageAndFriend = new MessageAndFriend();
        messageAndFriend.setMessageVo(messageVo);
        messageAndFriend.setSender(sender);

        return messageAndFriend;
    }

    @Autowired
    private Result result;

    public Map<String, Object> findFriendsAndMessage(Long curUid, Long friendId, String curPage){
//        System.out.println("查找好友以及和好友的聊天记录");
        List<Message> mySends = messageService.findMessagesBySidAndRid(curUid, friendId);
        List<Message> myReceives = messageService.findMessagesBySidAndRid(friendId, curUid);

        List<Message> messages = mergeMessageList(mySends, myReceives);  // 双方聊天记录
//        System.out.println("our messages: "+ messages);

        if(messages == null || messages.isEmpty()){
            return result.resultMap(false, "和当前好友暂无聊天记录", messages);
        }

        List<MessageAndFriend> messageAndFriends = new ArrayList<>();
        for(Message message: messages){
            MessageAndFriend messageAndFriend = findFriendAndMessage(message, curPage);
            messageAndFriends.add(messageAndFriend);
        }

        return result.resultMap(true, "查询聊天记录成功", messageAndFriends);
    }
}
